<?php
//	user.inc.php
// 	This file contains most of the functions related to user management (Login, Registration,...)
// 	See also, for the functions that uses the class:User, user.class.php

//////////////////////////////////////////////////////////////////////////////////////////
// AUTHENTIFICATION INCLUDE // THIS ALLOWS EVERY PAGE TO CONNECT OR DISCONNECT THE USER //
//////////////////////////////////////////////////////////////////////////////////////////
//Since it is using cookies, this must figures here. It is included before <!DOCTYPE and header.
//We suppose that the user isn't initally connected.
$connected=false;

//	This is called by the user pannel when user changes his password.
// 	After being updated in database, we update user pwd cookie that contains sha1 hashed password used to keep him logged in
if(isset($_GET['copwd']) AND !empty($_GET['copwd'])) 
						{
						if(!isset($_GET['reloaded']))
						{
						setcookie("pwd", "", time() - 3600, "/");
						echo'<script>
						window.location.href = "account.php?reloaded=yes&copwd='.$_GET['copwd'].'"
						</script>'; 
						}
						if(isset($_GET['reloaded']) AND $_GET['reloaded']=="yes")
						{
						setcookie("pwd", $_GET['copwd'], time() + (86400 * 30), "/");
						echo'<script>
						window.location.href = "account.php"
						</script>';   
							}
		}


// This is required when user tries to log in using the pop-up form available in the menu or the loginform in the register page.
// For the pop-up form login, this redirects to the actual page 
// For the log in form in the register page, it redirects to the user pannel						
if(isset($_POST['log_email']) AND isset($_POST['log_password'])) //user just attempted to login
{	
	if(check_login($db,$_POST['log_email'],sha1($_POST['log_password']))!=false) //Function check_login allows to check user login information
	{	
		$connected=true; //this boolean is true when the connection is successful and false when not.
		session_start(); // user connected, session starts
		$_SESSION['id'] = check_login($db,$_POST['log_email'],sha1($_POST['log_password'])); // when not false, function check_login returns user ID
		setcookie("id", $_SESSION['id'], time() + (86400 * 30), "/");
		setcookie("pwd", sha1($_POST['log_password']), time() + (86400 * 30), "/");
		$user= new User($db,$_SESSION['id']);
	}
	else{ $connected=false; $error['notconnected']="Sorry, but it looks like the information you entered in the login form are incorrect. Try again."; } // Connexion failed.
}

else{ // No form was submitted
		if(isset($_COOKIE['id']) AND isset($_COOKIE['pwd'])) // user may connect automatically using cookies
		{ // Two cookies are stored
			// id: this stores the user ID 
			// pwd: stores the user password
						
			$user= new User($db,$_COOKIE['id']); // retrieving user information using the ID
			if(check_login($db,$user->email,$_COOKIE['pwd'])!=false) // if ID and hashed password are successful, user is connected
			{
				$connected=true;
				session_start(); // and we start the session
				$_SESSION['id'] = check_login($db,$user->email,$_COOKIE['pwd']); // when not false, function check_login returns user ID
				$user->updateIP($db); //updating user's last known IP address
			}
			else{ $connected=false; } // cookie connexion failed.

		}
}

// Logout function (can be called from any page), that destroy cookies.
	if(isset($_GET['op']) AND $_GET['op']=="logout")
	{	
		setcookie("id", "", time() - 3600, "/");
		setcookie("pwd", "", time() - 3600, "/");
		echo'<script language=javascript>
		document.location = "index.php";
		</script>';
	}

//////////////////////////////////////////////////////////////////////////////////////////
// ACCOUNT LOGIN, REGISTRATION AND MANAGEMENT FUNCTIONS								    //
//////////////////////////////////////////////////////////////////////////////////////////
function send_activation_mail($email, $firstname, $actcode, $transport, $website_url)
{ // USING SWIFT LIBRARY

$to = $email;
$subject = "Jönkötrade - Activate your account";
$headers = "MIME-Version: 1.0" . "\r\n";
$from='<jonkotrade@gmail.com>';
$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$body = '
<html>
<head>
<title>Validation e-mail</title>
</head>
<body>
<h1>Congratulations. Welcome to Jönkötrade</h1> 
<p>In order to activate your account, you must access this link (copy/paste if not clickable):<br/> <a href="'.$website_url.'/account.php?op=activate&code='.$actcode.'">'.$website_url.'/account.php?op=activate&code='.$actcode.'</a></p>
</body>
</html>
';

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance($subject)
  ->setFrom(array('jonkotrade@gmail.com'))
  ->setTo(array($to))
  ->setBody($body,'text/html');

$result = $mailer->send($message);

}

function send_mail($email, $sujet, $body)
{ // USING SWIFT LIBRARY

$to = $email;
$subject = "Jönkötrade - " . $sujet;
$headers = "MIME-Version: 1.0" . "\r\n";
$from='<jonkotrade@gmail.com>';
$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance($subject)
  ->setFrom(array('jonkotrade@gmail.com'))
  ->setTo(array($to))
  ->setBody($body,'text/html');

$result = $mailer->send($message);

}

function cryptandcompare($data,$hash_data)
{ // used to compare transparent input data with encrypted data. Suitable for passwords and the home-made captcha script
	if($hash_data==sha1($data))
	{
	return true;
	}
	else { return false; }

}

function randomString($lenght)
		{
		//Random string generator (for my home made captcha using canvas)
				//First, let's generate a random string
				$random = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $lenght);  //for Login in (short string)
				return $random;
		}


function calculate_age($birth)
{ // Since I'm not very comfortable with dates, this function was widely inspired by a stackoverflow post.
// I lost the URL, but I can't decently pretend this to be mine.
$tdate = time();
		$age = 0;
		$strbirth= strtotime($birth);
		while( $tdate > $strbirth = strtotime('+1 year', $strbirth))
			{
				++$age;
			}
			return $age;
}


function create_user($db, $email, $password, $gender, $firstname, $surname, $phone, $birth, $address, $picture, $active, $acctype, $regdate, $lastip)
    { // This function handles account registration. You musn't call it until you have previously checked the account data (valid inputs) using function check_user_data()
		$hash_password=sha1($password);
		// Checking database connection //
				try
				{ $db; }
				catch(Exception $e) //if there's some trouble
				{ die('Error connecting to the database : '.$e->getMessage()); }
		
		// Database connected. Let's process //
		
				$req = $db->prepare('INSERT INTO jktrade_users(email, pwd, gender, firstname, surname, phone, birth, address, active, regdate, last_ip, acctype) 
												VALUES(:email, :password, :gender, :firstname, :surname, :phone, :birth, :address, :active, :regdate, :last_ip, :acctype)');
				$req->execute(array(
					'email' => $email,
					'password' => $hash_password,
					'gender' => $gender,
					'firstname' => $firstname,
					'surname' => $surname,
					'phone' => $phone,
					'birth' => $birth,
					'address' => $address,
					'active' => $active,
					'regdate' => $regdate,
					'last_ip' => $lastip,
					'acctype' => $acctype
					));
	    }
		

function check_user_data($db, $email, $password, $gender, $firstname, $surname, $phone, $birth, $address, $acctype, $captcha, $hash_captcha, $transport, $website_url)
{ // Please note that in this function, $password isn't crypted. It directly uses the $_POST['password'].
// Captcha is the captcha sent by user. $hash_captcha is the crypted, original captcha.
$errors=false; // let's suppose there's no error for the moment.
// First check: does the "e-mail" seems to be a valid email ? 
if(!filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($email))
{
$error['mail']="Your e-mail doesn't seem right. It must looks like domain@example.com";
$errors=true; // if there's an error somewhere, this is true. 
}

// Second check: the email may be valid, but does it already exists in the database ?
$req = $db->prepare('SELECT id FROM jktrade_users WHERE email = :email');
					$req->execute(array('email' => $_POST['email']));
					$result = $req->fetch();

if($result)// mail found
{
$error['mail']="Looks like this email is already used.";
$errors=true;
}

//Password. Let's see if it is, at least, 6 characters long. This restriction can be modified in config.inc.php
if((strlen($password)<MIN_PWD_LENGHT) OR empty($password))
{
$error['password']="Looks like your password is less than 6 characters. Pick another one !";
$errors=true;
}

//Firstname, Surname: Checking if they are only alphabetical
 preg_match("/([^A-Za-z])/",$firstname . $surname,$abccheck); //let's just concatenate the strings instead of checking each of them separatly
if(!empty($abccheck) OR empty($firstname) OR empty($surname)) // There's something else than alphabet
{
$error['name']="Your first name / surname can contain only alphabetic characters";
$errors=true;
}

//Phone number: let's see if it's only made out of numbers 
if(!preg_match("'^[0-9]{9,13}[0-9]$'", $phone) OR empty($phone)) // There's something else than numbers
{
$error['phone']="Your phone number doesn't seem valid. It must contains from 9 to 13 digits.";
$errors=true;
}

//Birth day: let's see if it's in the right format and user aged at least 18
if(!preg_match( "'^\d{4}-\d{2}-\d{2}$'" , $birth ) OR empty($birth))
{
$error['birth']="Your birthday isn't in the correct format. It must look like YYYY-MM-DD";
$errors=true;
}
else{ 
		
		if(calculate_age($birth)<18)
		{
		$error['birth']="You must be aged at least 18 to use our services.";
		$errors=true;
		}		

}

// Captcha verification:
if(!cryptandcompare($captcha,$hash_captcha)) //doesn't matching
{
		$error['captcha']="You entered the wrong captcha. Are you a human ?";
		$errors=true;
}

if(empty($address)) //no address
{
		$error['address']="You must enter your address";
		$errors=true;
}

if($errors) //something went wrong
{
$captcha=randomString(7);
// Generating new register form adapted to the situation
echo'<h2><span style="text-transform: uppercase;">Oops... There is a mistake somewhere !</span></h2>
			
			<p>
				Make sure the information are correct and try again. 
			</p>
			<p>
				<form novalidate="novalidate" method="post" action="account.php" id="register-form" class="register-form"/>
					
					<p class="form_info" style="font-size:1em;">
					Log-in information
					<span class="required" >*</span>
						</p>
					';
					if(isset($error['mail']))
					{
					echo'
					<small style="color:red" >'.$error['mail'].'</small>
					<input class="error"  name="email" id="email" value="'.$email.'" type="email"/>
					';
					}
					else
					{
					echo'<input value="'.$email.'" name="email" id="email"  type="email"/>';
					}
					
					if(isset($error['password']))
					{
					echo'
					<small style="color:red" >'.$error['password'].'</small>
					<input class="error" name="password" id="password" type="password" value="'.$password.'"/><br><br/>
					';
					}
					else
					{
					echo'<input value="'.$password.'" name="password" id="password" type="password"/><br><br/>';
					}
					
					echo'
					
					<p class="form_info" style="font-size:1em;">
					Personal information
					<span class="required" >*</span>
						</p>
						
					<select name="gender" id="gender" placeholder="Gender" style="width:230px;">
					<option value="male">Mr.</option>
					<option value="female">Mrs.</option>
					</select><br/> ';
					
					if(isset($error['name']))
					{
					echo'
					<small style="color:red" >'.$error['name'].'</small>
					<input class="error" name="firstname" id="firstname" value="'.$firstname.'" type="text"/>
					<input class="error" name="surname" id="surname" value="'.$surname.'" type="text"/>
					';
					}
					else
					{
					echo'<input value="'.$firstname.'" name="firstname" id="firstname"  type="text"/>
					<input value="'.$surname.'" name="surname" id="surname"  type="text"/>';
					}
					
					if(isset($error['birth']))
					{
					echo'
					<small style="color:red" >'.$error['birth'].'</small>
					<input class="error" name="birth" id="birth" value"'.$birth.'"  type="text"/>
					';
					}
					
					else
					{
					echo'<input type="text"  value="'.$birth.'" name="birth"/> ';
					}
					
					if(isset($error['phone']))
					{
					echo'
					<small style="color:red" >'.$error['phone'].'</small>
					<input class="error" name="phone" id="phone" value="'.$phone.'" type="text"/>
					';
					}
					else
					{
					echo'<input value="'.$phone.'" name="phone" id="phone" type="text"/><br><br/>';
					}
					
					if(isset($error['address']))
					{
					echo'
					<textarea name="address" class="error" id="address" placeholder="You must enter an address"  style="min-height: 120px;">'.$address.'</textarea><br></br>';
					}
					else{
					echo'<textarea name="address" id="address" placeholder="Address"style="min-height: 120px;">'.$address.'</textarea><br></br>';
					}
					echo'
					<p class="form_info" style="font-size:1em;">
					Captcha / Anti-bot security
					<span class="required" >*</span>
						</p>';
					
					if(isset($error['captcha']))
					{
					echo'
					<small style="color:red" >'.$error['captcha'].'</small><br/>
					<canvas id="captchaR" width="230" height="50" style="border: 1px solid red; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px;"></canvas>
					<script>
					var ctxR = document.getElementById(\'captchaR\').getContext(\'2d\');
					var kittyR = new Image();
					kittyR.src = \'img/captchagrid.png\';
					kittyR.onload = function(){
					  ctxR.drawImage(this, 0,0,this.width, this.height);
					  ctxR.font         = \'45px Tequillasunrise\';
					  ctxR.fillStyle = \'#333399\';
					  ctxR.textBaseline = \'top\';
					  ctxR.fillText  (\''.$captcha.'\', 10, 2);
					};
					</script><br/>
					<input class="error" name="captcha" id="captcha" placeholder="Retype captcha..." type="text" style="width:230px;"/><br><br/>
					<input type="hidden" name="cc" value="'.sha1($captcha).'" />
					';
					}
					
					else
					{
					echo'
					<canvas id="captchaR" width="230" height="50"></canvas>
					<script>
					var ctxR = document.getElementById(\'captchaR\').getContext(\'2d\');
					var kittyR = new Image();
					kittyR.src = \'img/captchagrid.png\';
					kittyR.onload = function(){
					  ctxR.drawImage(this, 0,0,this.width, this.height);
					  ctxR.font         = \'45px Tequillasunrise\';
					  ctxR.fillStyle = \'#333399\';
					  ctxR.textBaseline = \'top\';
					  ctxR.fillText  (\''.$captcha.'\', 10, 2);
					};
					</script><br/>
					<input name="captcha" id="captcha" placeholder="Retype captcha..." type="text" style="width:230px;"/><br><br/>
					<input type="hidden" name="cc" value="'.sha1($captcha).'" />
					';
					}
					
					
					
					echo'
					
					<p><label> I have read and accept <a>the terms of condition</a>.<br/> We won\'t share your personal data with third party companies.</label></p>
					<input type="hidden" name="op" value="register" />
					<input type="hidden" name="active" value="notyet" />
					<input value="Register!" class="btn btn-primary" type="submit">
				</form>
			</p>

';
}

else // everything went fine, let's register the user
{
$activation_code=randomString(15);
create_user($db, $email, $password, $gender, $firstname, $surname, $phone, $birth, $address, 'img/avatar-default.gif', $activation_code, $acctype, date("Y-m-d H:i:s"), $_SERVER['REMOTE_ADDR']);
send_activation_mail($email, $firstname, $activation_code, $transport, $website_url);
echo' success !!';
}

}//end function


function check_login($db, $email, $hash_pwd)
    { // This function handles account login verification. 
	// it returns false if informations are wrong and no associated account was found in database
	// it returns user ID if the informations are correct. 
       
		// Checking database connection //
				try
				{ $db; }
				catch(Exception $e) //if there's some trouble
				{ die('Error connecting to the database : '.$e->getMessage()); }
		
		
		// Database connected. Let's process //
		$req = $db->prepare('SELECT id FROM jktrade_users WHERE email = :email AND pwd = :password');
		$req->execute(array(
			'email' => $email,
			'password' => $hash_pwd));
		$result = $req->fetch();
				
				if($result) // account found - password and email matching with an entry
				{return $result['id'];}
				else
				{return false;} //no account found - means invalid email or password
				
	    }
		
function activate($db, $actcode)
		{
		$req = $db->prepare('SELECT id FROM jktrade_users WHERE active = :activate');
					$req->execute(array('activate' => $actcode));
					$result = $req->fetch();
		if($result)
		{ // activation code found, let's activate associated user
		$db->exec('UPDATE jktrade_users SET active = "yes" WHERE id = '.$result['id'].'');
		return $result['id'];
		}
		else 
		{
		return false;
		}
		
	}
	



function updatecookie($value)
{ // my function for cookie update, suitable per example when user changes his password, to keep him connected.
echo'<script>
						window.location.href = "account.php?copwd='.$value.'"
						</script>';
}

function searchuser($db, $search, $field) // This function is suitable for inbox 
{
		if(empty($field)) // User is trying to mess up with us. He must search for someone in particular
		{
		echo'You must enter a term to look for<br/>';
		}
		else{ // Ok let's look for this user
				$getuser = $db->query('SELECT id FROM jktrade_users WHERE '.$field.'="'.$search.'" ORDER BY '.$field.'');
				while ($data = $getuser->fetch())
								{	
								$user = new User($db,$data['id']);
								echo'
								<table class="table table-striped">
									 <thead>
										 <tr>
											<th>User Name</th>
											<th>Mail</th>
											<th>Send</th>
										  </tr>
										</thead>
										<tbody>
										
										<tr>
											<td>'.$user->firstname . " " .$user->surname.'</td>
											<td>'.$user->email.'</td>
											<td><a href="account.php?page=inbox&op=sendPIM&user='.$user->id.'">SEND PIM</a></td>
											
										  </tr>
								
										</tbody>
									  </table>';
								}

		}


}
	
		

?>